package com.itheima.health.controller;

import com.aliyun.oss.ServiceException;
import com.itheima.health.common.R;
import com.itheima.health.model.pojos.OrderSetting;
import com.itheima.health.service.OrdersettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/ordersetting")
public class OrdersettingController {
    @Autowired
    private OrdersettingService ordersettingService;

    @GetMapping("/getOrderSettingByMonth")
    public R getOrderSettingByMonth(String month){
      List<OrderSetting> orderSettingList= ordersettingService.getOrderSettingByMonth(month);
        R r = new R();
        r.setFlag(true);
        r.setData(orderSettingList);
        return r;
    }
    @PostMapping("/upload")
    public R uploadExcel(@RequestParam("excelFile") MultipartFile file)throws Exception {
        log.info("开始上传Excel文件");
        R result = new R();
        try {
            if (file == null) {
                // 文件不能为空
                log.info("file参数为空！");
                result.setFlag(false);
                result.setMessage("file参数为空！");
                return result;
            }
            String fileName = file.getOriginalFilename();
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                // 文件格式不正确
                log.info("Excel文件格式不正确！");
                result.setFlag(false);
                result.setMessage("Excel文件格式不正确！");
                return result;
            }

            long size = file.getSize();
            if (StringUtils.isEmpty(fileName) || size == 0) {
                // 文件不能为空
                log.info("Excel文件内容为空！");
                result.setFlag(false);
                result.setMessage("Excel文件内容为空！");
                return result;
            }

            result = ordersettingService.uploadExcel(fileName,file,result);

            if (result.getMessage().equals("success")) {
                //保存成功
                log.info("上传Excel文件，文件上传成功！");
                result.setFlag(true);
                result.setMessage("上传Excel文件，文件上传成功！");
            }
        } catch (ServiceException e) {
            e.printStackTrace();
            result.setFlag(false);
            result.setMessage("上传Excel文件异常");
            log.error("上传Excel文件异常", e);
        }

        return result;
    }

}
